package com.gfm.story.interceptor;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.annotation.Resource;

/**
 * @BelongsProject: house-parent
 * @BelongsPackage: com.mooc.house.web.interceptor
 * @Author: Administrator
 * @CreateTime: 2019-04-24 15:55
 * @Description: ${Description}
 *                  WebMvcConfigurerAdapter:更改mvc配置
 */
@Configuration
public class WebMvcConf extends WebMvcConfigurerAdapter {

    /**
     * 注入已定义的两个拦截器
     */
    @Resource
    private  AuthActionInterceptor authActionInterceptor;
    @Resource
    private  AuthInterceptor authInterceptor;

    /**
     * 将拦截器注册到spring容器中
     * 实现添加拦截器，执行顺序由上往下
     * @param registry
     */
    public void addInterceptors(InterceptorRegistry registry) {
        /**
         * 添加拦截器addInterceptor，设置禁止拦截的路径/static，设置需要拦截的路径/**
         */
        registry.addInterceptor(authInterceptor).excludePathPatterns("/static").addPathPatterns("/**");
        /**
         * 添加拦截器authActionInterceptor，拦截所有需要登录才能访问的路径
         */
        registry.addInterceptor(authActionInterceptor).addPathPatterns("/house/toAdd")
                .addPathPatterns("/accounts/profile").addPathPatterns("/accounts/profileSubmit")
                .addPathPatterns("/house/bookmarked").addPathPatterns("/house/del")
                .addPathPatterns("/house/ownlist").addPathPatterns("/house/add")
                .addPathPatterns("/house/toAdd").addPathPatterns("/agency/agentMsg")
                .addPathPatterns("/comment/leaveComment").addPathPatterns("/comment/leaveBlogComment");
        super.addInterceptors(registry);//配置定义的拦截器
    }

    /**
     * 配置请求跨域
     * @param registry
     */
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                // 放行哪些原始域
                .allowedOrigins("*")
                // 是否发送Cookie信息
                .allowCredentials(true)
                // 放行哪些原始域(请求方式)
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                // 放行哪些原始域(头部信息)
                .allowedHeaders("*")
                // 暴露哪些头部信息（因为跨域访问默认不能获取全部头部信息）
                .exposedHeaders("Header1", "Header2");
        super.addCorsMappings(registry);
    }

}
